package com.hfi.restful.validator;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hfi.restful.exception.ErrorCode;
import com.hfi.restful.exception.MyException;
import org.apache.commons.collections4.MapUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

/**
 * @author ChangLiang
 * @date 2019/9/19
 */
public class BeanValidator {

    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    /**
     * 基础泛型方法 校验Bean
     *
     * @param t
     * @param groups 使用了java变长参数 为了在validate方法中使用
     * @param <T>
     * @return 将校验错误的字段和错误信息放到map中
     */
    public static <T> Map<String, String> validate(T t, Class... groups) {
        Validator validator = validatorFactory.getValidator();
        Set<ConstraintViolation<T>> validateResult = validator.validate(t, groups);
        if (validateResult.isEmpty()) {
            return Collections.emptyMap();
        }
        LinkedHashMap<String, String> errorsLinkedHashMap = Maps.newLinkedHashMap();
        Iterator<ConstraintViolation<T>> iterator = validateResult.iterator();
        while (iterator.hasNext()) {
            ConstraintViolation<T> violation = iterator.next();
            //将校验错误的字段和错误信息放到map中
            errorsLinkedHashMap.put(violation.getPropertyPath().toString(), violation.getMessage());
        }
        return errorsLinkedHashMap;
    }

    /**
     * 校验集合
     * @param collection
     * @return
     */
    public static Map<String, String> validateList(Collection<?> collection) {
        // 判断
        Preconditions.checkNotNull(collection);
        Iterator<?> iterator = collection.iterator();
        Map<String,String> errors;
        do {
            // 退出的终止条件
            if (!iterator.hasNext()) {
                return Collections.emptyMap();
            }
            Object object = iterator.next();
            // new Class[0] 为了参数与Object一致? 直接使用其值?
            errors = validate(object, new Class[0]);
            // 只要有一个对象校验不通过 那么就退出
        } while (errors.isEmpty());
        return errors;
    }

    /**
     * 任何校验都使用这一个方法
     * @param first 对象
     * @param objects 数组
     * @return
     */
    public static Map<String, String> validateObject(Object first, Object... objects) {
        if (Objects.nonNull(objects) && objects.length > 0) {
            return validateList(Lists.asList(first, objects));
        } else {
            return validate(first, new Class[0]);
        }
    }

    public static void check(Object param) {
        Map<String, String> map = BeanValidator.validateObject(param);
        if (MapUtils.isNotEmpty(map)) {
            ErrorCode errorCode = ErrorCode.PARAM_VALIDATION_FAIL;
            throw new MyException(errorCode, map);
        }
    }

}
